<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\PostPageRequest;
use App\Http\Requests\PostSaveRequest;
use App\Http\Requests\PostUpdateRequest;
use App\Http\Responses\Response;
use App\Models\Category;
use App\Models\Post;
use App\Models\PostDetail;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Response as Res;

class PostController extends Controller
{
    public function listByPage(PostPageRequest $request): JsonResponse
    {
        $paginator = Post::with(["tags", "category"])->paginate($request->validated()["size"]);
        return Response::select_one($paginator);
    }

    public function save(PostSaveRequest $request): JsonResponse
    {
        $post = Post::create($request->validated());
        $post->detail()->create($request->validated());
        if(isset($request->validated()['tags'])){
            $post->tags()->attach($request->validated()['tags']);
        }
        return Response::insert_success(Post::with(['detail', 'category', 'tags'])->find($post->post_id));
    }
    public function update(PostUpdateRequest  $request, $id): JsonResponse
    {
        $posts = Post::where("post_id", $id);
        if($posts->count() <= 0){
            return Response::not_found();
        }
        $post = $posts->get()[0];
        try{
            DB::beginTransaction();
            // 更新文章
            $post->update($request->validated());
            // 更新文章详情
            if($post->has('detail')->count() > 0){
                $post->detail()->get()[0]->update($request->validated());
            }
            else {
                $validator = Validator::make($request->validated(), [
                    "pd_content_raw" => "required",
                    "pd_content" => "required",
                    "pd_is_reward" => ["nullable", "integer", "max:1", "min:0"],
                    "pd_is_comment" => ["nullable", "integer", "max:1", "min:0"],
                    "pd_pwd" => "nullable"
                ]);
                if($validator->fails()){
                    throw new Exception(json_encode($validator->errors()->getMessages()));
                }
                $post->detail()->create($validator->validated());

            }
            // 更新标签
            if(isset($request->validated()['tags'])){
                $post->tags()->sync($request->validated()['tags']);
            }
            // 更新分类
            if(isset($request->validated()['cate_id'])){
                $cate_id = $request->validated()['cate_id'];
                if(Category::where("cate_id", $cate_id)->count() <= 0){
                    throw new Exception(json_encode(["cate_id" => "The selected cate_id is invalid."]));
                }
                $post->cate_id = $cate_id;
                $post->save();
            }
            DB::commit();
            return Response::update_success(Post::with(["detail", "tags", 'category'])->find($id));
        } catch (Exception $exception){
            DB::rollBack();
            return Res::json([
                "code" => 50002,
                "message" => json_decode($exception->getMessage())
            ]);
        }


    }

    public function delete($id): JsonResponse
    {
        $posts = Post::where("post_id", $id);
        if($posts->count() <= 0){
            return Response::not_found();
        }
        $post = $posts->get()[0];
        try {
            DB::beginTransaction();
            $post->detail()->delete();
            $post->tags()->detach();
            $post->delete();
            DB::commit();
            return Response::delete_success($post);
        } catch(Exception $exception) {
            DB::rollBack();
            return Response::delete_error();
        }
    }

    public function getTopPost(): JsonResponse
    {
        $posts = Post::where("post_is_top", 0)->with(["category", "tags"]);
        return Response::resource_success($posts);
    }

    public function findById($id): JsonResponse
    {
        if (Post::where('post_id',$id)->count() <= 0) {
           return Response::not_found();
        }

        $post = Post::with(["detail", "category", "tags"])->find($id);
        return Response::select_one($post);
    }

}
